package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strconv"
)

func loop() {
	arr := [5]int{1, 2, 3, 4, 5}
	// 对于数组,字符串,切片 可以使用For-each range这种循环
	for i := range arr {
		fmt.Println(arr[i])
	}

	for i, s := range arr {
		fmt.Printf("arr数组在索引: %d 的值为: %d \n", i, s)
	}
}

func loop1() {
	arr := [5]int{1, 2, 3, 4, 5}
	//标准 for 循环
	for i := 0; i < len(arr); i++ {
		fmt.Println(arr[i])
	}

}

func convertToBin(n int) string {
	result := ""
	if n == 0 {
		result = "0"
		return result
	}
	//可以不指定初始条件
	for ; n > 0; n /= 2 {
		lsb := n % 2
		result = strconv.Itoa(lsb) + result
	}
	return result
}

func printFile(filename string) {
	reader, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	printFileContents(reader)
}

func printFileContents(reader io.Reader) {
	scanner := bufio.NewScanner(reader)

	//可以直接使用 bool 相当于 while (condition) {}
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

}

func forever() {
	//死循环,相当于 while true
	for {
		fmt.Println("aaa")
	}
}

func main() {
	fmt.Println(convertToBin(4), convertToBin(10), convertToBin(0))
	printFile("abc.txt")
	loop()
	loop1()
	//forever()
}
